package com.linln.admin.welfare.service.impl;

import com.linln.admin.welfare.domain.Self;
import com.linln.admin.welfare.repository.SelfRepository;
import com.linln.admin.welfare.service.SelfService;
import com.linln.common.data.PageSort;
import com.linln.common.enums.StatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @author wcy
 * @date 2020/03/14
 */
@Service
public class SelfServiceImpl implements SelfService {

    @Autowired
    private SelfRepository selfRepository;

    /**
     * 根据ID查询数据
     * @param id 主键ID
     */
    @Override
    @Transactional
    public Self getById(Long id) {
        return selfRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<Self> getPageList(Example<Self> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return selfRepository.findAll(example, page);
    }

    /**
     * 保存数据
     * @param self 实体对象
     */
    @Override
    public Self save(Self self) {
        return selfRepository.save(self);
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return selfRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    @Override
    public Self getByUserId(Long deptId) {
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();

        Self self = new Self();
        self.setUserId(deptId);
        // 获取数据列表
        Example<Self> example = Example.of(self, matcher);
        Optional<Self> result = selfRepository.findOne(example);
        if (!result.isPresent()){
            return self;
        }
        return result.get();
    }
}